/**地图模板服务**/
(sbGis.register || sbGis).factory("$SbLayerDataQueryVector", function($SbTipModal, $http, $q, $SbMainMapParam, $SbMapUtil, $SbPostDownload, $SbResourceLoading, $SbLayerDataProjectChange, $SbMapLayerFunc) {
    // var queryUrl = basePath + "/dataOperate/query";
    var queryUrl = dcServerUrl + "/dc/operate/dataSetId/query";
    var wktFormat = new ol.format.WKT();
    var queryIndex = 0;
    // var parser = new jsts.io.OL3Parser();
    var getConnectPromise = function(url, config) {
        config = angular.extend({url: url, type: "POST", xhrFields: {withCredentials: true}}, config);
        return $.ajax(config);   // 返回承诺，这里并不是最终数据，而是访问最终数据的API
    };
    //临时处理
    var defectPipelineWtdh = [];
    var gdDataIdArr = ["ps_jcj", "ps_jxj", "ps_ysj", "ps_wb", "ps_yb", "ps_ysb", "ps_ylj"];

    var changeToFeature = function(dataSetId, result) {
        var olFeatures = [];
        var data = $SbMainMapParam.getLayerConfig("l_" + dataSetId);
        for (var i = 0; result && i < result.length; i++) {
            var property = result[i];
            if (defaultProjectId == "p_pipeline" && (dataId == "ps_pipe") && property.qxdj > 1 && !property.objectid) {
                defectPipelineWtdh.push(property.qdwtdh);
                defectPipelineWtdh.push(property.zdwtdh);
            }

            if (defaultProjectId == "p_pipeline" && gdDataIdArr.indexOf(dataId) > -1 && defectPipelineWtdh.indexOf(property.remark) < 0 && !property.objectid) {

            } else {
                var key = property[data.keyName];
                var wkt = property[data.geometryName];

                delete property[data.geometryName];

                var olFeature = new ol.Feature();
                olFeature.setId(key);
                olFeature.setProperties(property);
                var geometry;
                try {
                    if (wkt.indexOf("Z") >= 0 || wkt.indexOf("M") >= 0) {
                        wkt = wkt.replace(/(ZM|Z|M)(\s)*\(/, "(");
                        var newWkt = "";
                        var temp = "";
                        for (var j = 0; j < wkt.length; j++) {
                            if (wkt[j] == "(" || wkt[j] == ")" || wkt[j] == ",") {
                                //处理temp;
                                var r = temp.trim().split(" ");
                                if (r.length == 4 || r.length == 3) {
                                    temp = r[0] + " " + r[1];
                                }
                                newWkt += temp;
                                temp = "";
                                newWkt += wkt[j];
                            } else {
                                temp += wkt[j];
                            }
                        }
                        wkt = newWkt;
                    }
                    geometry = wktFormat.readGeometry(wkt);
                } catch (e) {
                    geometry = undefined;
                }
                geometry = $SbLayerDataProjectChange.transformMap(geometry, dataSetId);
                olFeature.setGeometry(geometry);
                olFeatures.push(olFeature);
            }
        }
        return olFeatures;
    };

    var changeToVectorParam = function(param) {
        var queryObjects = $SbMapUtil.changeQueryObjectToNewObjects(param.queryObjects) || [];
        if (param.queryGeometry) {
            var arr = [];
            for (var i = 0; i < param.queryGeometry.length; i++) {
                if (param.queryGeometry[i] instanceof ol.geom.Geometry) {
                    var geom = param.queryGeometry[i];
                    if (geom instanceof ol.geom.Circle) { //如果是圆
                        var circle = param.queryGeometry[i];
                        param.queryGeometry[i] = ol.geom.Polygon.fromCircle(circle);
                    } else if (geom instanceof ol.geom.Point) { //如果是点
                        var point = param.queryGeometry[i];
                        var circle = new ol.geom.Circle({
                            center: point.getCoordinates(),
                            radius: $SbMapUtil.transforDistance(30, $SbMainMapParam.getMapUnit()),
                        });
                        param.queryGeometry[i] = ol.geom.Polygon.fromCircle(circle);
                    } else if (geom instanceof ol.geom.LineString) { //如果是线
                        var line = param.queryGeometry[i];
                        // 转换成 JSTS geometry
                        var jstsGeom = parser.read(line);

                        // 创建缓冲
                        var buffered = jstsGeom.buffer($SbMapUtil.transforDistance(30, $SbMainMapParam.getMapUnit()));

                        // 转换成 ol geometry
                        param.queryGeometry[i] = parser.write(buffered);
                    }
                    var geometry = $SbLayerDataProjectChange.transformBack(param.queryGeometry[i], param.projectLayerId);
                    arr.push(wktFormat.writeGeometry(geometry));
                }
            }
            var data = $SbMainMapParam.getLayerConfig("l_" + param.projectLayerId);

            if (arr.length > 0) {
                if ($SbMapUtil.isRectangle(geometry)) {
                    queryObjects.push([data.geometryName, "env_intersects", arr[0]]);
                } else {
                    queryObjects.push([data.geometryName, "intersects", arr[0]]);
                }
            }
        }

        if (queryObjects.length > 1) {
            queryObjects.push("and");
        } else if (queryObjects.length == 1) {
            queryObjects = queryObjects[0];
        } else {
            queryObjects = null;
        }
        /*   var aParam0 = {
               dataId : param.projectLayerId,
               queryXzqh:param.queryXzqh,
               quickSearchValue : param.queryValue,
               queryFieldsStr : param.queryFields?JSON.stringify(param.queryFields):null,
               queryObjectsStr : queryObjects?JSON.stringify(queryObjects):null,
               // queryObjects : $SbMapUtil.changeQueryObjectToNewObjects(queryObjects),
               orderbyField : param.orderField,
               orderbyType : param.orderType,
               searchCount :  param.returnTotal,
               searchResult : true,
               returnGeometry : param.returnGeometry,
           };*/

        var aParam = {
            dataSetId: param.projectLayerId,
            // queryXzqh:param.queryXzqh,
            // quickSearchValue : param.queryValue,
            queryFields: param.queryFields,
            queryObjects: queryObjects,
            // queryObjects : $SbMapUtil.changeQueryObjectToNewObjects(queryObjects),
            orderbyField: param.orderField,
            orderbyType: param.orderType,
            searchCount: param.returnTotal,
            searchResult: true,
            returnGeometry: param.returnGeometry,
        };

        if (param.page) {
            aParam.rows = param.page.rows;
            aParam.page = param.page.page;
        }
        return aParam;
    };

    var service = {};

    return service;
});
